<template>
   <Card>
    <div style="margin: 10px;overflow: hidden">
        <div style="float: left;">
          <ButtonGroup shape="circle" size="small">
            <Button @click="addAction">新增</Button>
            <Button @click="refreshAction">刷新</Button>
          </ButtonGroup>
        </div>
        <div style="float: right;">
            <Page :total="totalCount" :current="pageIndex" :page-size="pageSize" @on-change="changePage" size="small"  show-total show-elevator></Page>
        </div>
    </div>
    <Table :data="tableData" :columns="tableColumns" :loading="listLoading" size="small" stripe></Table>

    <Modal
        :title="modalTitle"
        v-model="editModalShow"
        :mask-closable="false"
        :closable="false"
        :footer-hide="true"
        scrollable
        class-name="vertical-center-modal">
      <Form ref="editForm" :model="formData" label-position="right" :rules="validateRule" :label-width="100">
        <input v-model="formData.roleId" name="roleId" type="hidden">
        <FormItem label="角色名称" prop="roleName">
            <Input v-model="formData.roleName" name="roleName" placeholder="角色名称" />
        </FormItem>
        <FormItem label="角色描述">
            <Input v-model="formData.roleDescription" name="roleDescription" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="角色描述" />
        </FormItem>
        <FormItem>
           <div style="float: right;">
             <Button style="margin-right: 10px" @click="cancel">取消</Button>
            <Button type="primary" @click="saveHandle">保存</Button>
           </div>
        </FormItem>
      </Form>
    </Modal>

    <Modal
        :title="authoriseModalTitle"
        v-model="authoriseModal"
        :mask-closable="false"
        :closable="true"
        :footer-hide="true"
        width="760"
        scrollable
        class-name="vertical-center-modal">
         <Layout>
      <Sider hide-trigger :style="{background: '#fff', width: '260px', maxWidth: '220px', flex: '0 0 220px'}">
        <Card title="应用" icon="md-apps" :padding="5" shadow style="width: 210px; margin:0px 5px;">
          <CellGroup @on-click="onclientSelected">
            <Cell v-for='(client, index) in clients' :title='client.clientName' :selected='client.selected' :name="index" />
          </CellGroup>
        </Card>
      </Sider>
      <Content :style="{padding: '0px', minHeight: '280px', background: '#fff'}">
        <Card :title="authoriseContextTitle" icon="md-apps" :padding="5" shadow style="margin:0px 5px;">
          <div style="float: right;"  slot="extra">
          <ButtonGroup>
            <Button type="primary" @click="saveAuthoriseHandle">保存选中应用授权项</Button>
          </ButtonGroup>
          </div>
          <Tree ref="authoriseTree" :data="treeNodes" :render="renderTreeNode"  show-checkbox></Tree>
        </Card>
      </Content>
    </Layout>
    </Modal>
  </Card>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  name: 'UserRole',
  data () {
    return {
      tableColumns: [
        {
          type: 'index',
          title: '序号',
          align: 'center',
          width: 60
        },
        {
          title: '角色名称',
          key: 'roleName'
        },
        {
          title: '更新时间',
          key: 'updateTime'
        },
        {
          title: '操作',
          key: 'roleId',
          align: 'center',
          fixed: 'right',
          width: 200,
          render: (h, params) => {
            return h('div', [
              h('Button', {
                props: {
                  type: 'default',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.editAction(params)
                  }
                }}, '编辑'),
              h('Button', {
                props: {
                  type: 'default',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: () => {
                    this.deleteAction(params)
                  }
                }}, '删除'),
              h('Button', {
                props: {
                  type: 'default',
                  size: 'small'
                },
                on: {
                  click: () => {
                    this.authorizeAction(params)
                  }
                }}, '授权')
            ])
          }
        }
      ],
      tableData: [
        {
          roleId: '093e1f5ff1e44e1eb188a7cc6f2a1bc3',
          roleName: '管理员',
          updateTime: '2018-09-03'
        },
        {
          roleId: '093e1f5ff1e44e1eb188a7cc6f2a1bc4',
          roleName: '普通操作员',
          updateTime: '2018-09-03'
        }
      ],
      pageSize: 10,
      totalCount: 100,
      pageIndex: 1,
      listLoading: false,
      editModalShow: false,
      modalTitle: '角色添加',
      formData: {
        roleName: '',
        roleDescription: ''
      },
      validateRule: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      },
      // 应用及资源
      userRoleSelected: {},
      clients: [],
      clientsLoaded: false,
      clientSelectedIndex: 0,
      clientSelected: {},
      resources: {},
      treeNodes: [],
      authoriseModal: false,
      authoriseModalTitle: '用户授权',
      authoriseContextTitle: '请选择授权',
      // 指定应用、角色的资源数组
      roleResources: []
    }
  },
  methods: {
    ...mapActions('userRoleStore', [
      'loadUserRoleList', 'save', 'delete', 'listRoleResourcs', 'saveResources'
    ]),
    ...mapActions({
      loadClientAll: 'clientStore/loadAll',
      loadClientResources: 'resourceStore/listAll'
    }),
    loadClients: function () {
      return new Promise((resolve, reject) => {
        if (!this.clientsLoaded) {
          this.loadClientAll()
            .then(Response => {
              this.clients = Response.data
              this.clientsLoaded = true
              this.$Message.info('加载应用信息成功')
              resolve()
            },
            (error) => {
              this.$Message.error('加载应用信息失败')
              reject(error)
            })
        } else {
          resolve()
        }
      })
    },
    loadlist: function () {
      this.listLoading = true

      const pageInfo = {
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      this.loadUserRoleList(pageInfo)
        .then(res => {
          this.totalCount = res.data.total
          this.tableData = res.data.list
          this.listLoading = false
        })
        .catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    clearFormData: function () {
      this.formData = {
        roleName: '',
        roleDescription: ''}
    },
    changePage: function (currentPageIndex) {
      this.pageIndex = currentPageIndex
      this.loadlist()
      // this.$Message.info('当前页码:' + this.pageIndex)
    },
    refreshAction: function () {
      this.loadlist()
    },
    addAction: function () {
      this.clearFormData()
      this.modalTitle = '新增角色'
      this.editModalShow = true
    },
    editAction: function (params) {
      this.modalTitle = '角色编辑'
      this.editModalShow = true
      this.formData = {
        roleId: params.row.roleId,
        roleName: params.row.roleName,
        roleDescription: params.row.roleDescription}
    },
    deleteAction: function (params) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定要删除么？',
        onOk: () => {
          this.deleteHandle(params)
        }
      })
    },
    authorizeAction (params) {
      this.userRoleSelected = params.row
      // console.log('userRoleSelected', this.userRoleSelected)
      this.loadClients()
        .then(() => {
          return this.onclientSelected(0)
        })
      this.authoriseModalTitle = '请为[' + params.row.roleName + ']角色授权'
      this.authoriseModal = true
    },
    deleteHandle: function (params) {
      this.delete({
        roleId: params.row.roleId
      }).then(res => {
        // console.log(res)
        this.$Message.info('删除成功')
        this.loadlist()
      }).catch(() => {
        // console.error(err)
        this.$Message.error('删除失败')
      })
    },
    saveHandle: function () {
      this.$refs['editForm'].validate((valid) => {
        if (!valid) {
          this.$Message.error('输入信息不合法')
        } else {
          // console.log(this.formData)
          const data = {
            roleId: this.formData.roleId,
            roleName: this.formData.roleName,
            roleDescription: this.formData.roleDescription
          }
          this.save(data).then(res => {
            this.clearFormData()
            this.editModalShow = false
            this.$Message.info('保存成功')
            this.loadlist()
          }).catch(() => {
            this.$Message.info('保存失败')
          })
        }
      })
    },
    cancel: function () {
      this.editModalShow = false
    },
    renderTreeNode (h, { root, node, data }) {
      // console.log('>>>', data)
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', data.title)
        ])
      ])
    },
    // 授权界面中应用选中事件处理
    onclientSelected (index) {
      // console.log(' select click', index)
      return new Promise((resolve, reject) => {
        let oldSelectedItem = this.clients[this.clientSelectedIndex]
        oldSelectedItem.selected = false
        this.$set(this.clients, this.clientSelectedIndex, oldSelectedItem)

        let selectedItem = this.clients[index]
        selectedItem.selected = true
        this.$set(this.clients, index, selectedItem)
        this.clientSelectedIndex = parseInt(index)
        this.clientSelected = this.clients[this.clientSelectedIndex]
        this.treeNodes = []

        let { roleId } = this.userRoleSelected
        let { clientId } = this.clientSelected
        // console.log('roleId:', roleId, 'clientId', clientId)
        this.listRoleResourcs({roleId, clientId})
          .then((Response) => {
            this.roleResources = Response.data
            return Promise.resolve()
          }, (err) => {
            reject(err)
          })
          .then(() => {
            if (this.resources[this.clientSelected.clientId]) {
              // console.log(this.resources[this.clientSelected.clientId])
              let nodes = []
              this.nodesBuild(nodes, ['', null])

              this.treeNodes = nodes
              resolve()
            } else {
              this.loadClientResources({ clientId: this.clientSelected.clientId })
                .then(Response => {
                  this.resources[this.clientSelected.clientId] = Response.data

                  let nodes = []
                  this.nodesBuild(nodes, ['', null])
                  this.treeNodes = nodes

                  resolve()
                })
            }
          })
      })

      // 加载权限树数据
      // this.loadData()
      // console.log(this.getSelectedClientId())
    },
    nodesBuild: function (nodes, parentId) {
      for (let idx in this.resources[this.clientSelected.clientId]) {
        let resource = this.resources[this.clientSelected.clientId][idx]
        if (parentId.indexOf(resource.parentId) > -1) {
          let node = {
            nodeKey: resource.resourceId,
            title: resource.resourceName,
            clientId: resource.clientId,
            resourceId: resource.resourceId,
            resourceName: resource.resourceName,
            parentId: resource.parentId,
            url: resource.url,
            permission: resource.permission,
            orderValue: resource.orderValue,
            expand: true,
            children: []
          }
          let childs = this.resources[this.clientSelected.clientId].filter(res => {
            return res.parentId === resource.resourceId
          })
          if (this.roleResources && this.roleResources instanceof Array && this.roleResources.indexOf(resource.resourceId) > -1 && childs.length < 1) {
            node.checked = true
          }
          this.nodesBuild(node.children, [resource.resourceId])
          nodes.push(node)
        }
      }
    },
    saveAuthoriseHandle () {
      let checkedNodes = this.$refs['authoriseTree'].getCheckedNodes()
      // console.log(checkedNodes, this.userRoleSelected, this.clientSelected)
      let roleResource = {
        clientId: this.clientSelected.clientId,
        roleId: this.userRoleSelected.roleId,
        resourceIds: []
      }
      for (let idx in checkedNodes) {
        roleResource.resourceIds.push(checkedNodes[idx].resourceId)
      }
      // console.log(roleResource)
      this.saveResources(roleResource)
        .then((Response) => {
          this.authoriseModal = false
          this.$Message.info('授权保存成功')
        })
        .catch(() => {
          this.$Message.error('授权保存失败')
        })
    }
  },
  created () {
    this.loadlist()
  }
}
</script>

<style>

</style>
